// Minimal client-side fallback for pages where a userscript or injected code
// expects `window.$`/`window.jQuery`. Prefer disabling/modifying the
// offending userscript — this file is a safe fallback to avoid uncaught
// ReferenceError in the console when jQuery isn't present.

export default defineNuxtPlugin(() => {
  // Minimal client-side fallback for pages where a userscript or injected code
  // expects `window.$`/`window.jQuery`. Prefer disabling/modifying the
  // offending userscript — this file is a safe fallback to avoid uncaught
  // ReferenceError in the console when jQuery isn't present.

  if (typeof window === 'undefined') return

  if (typeof window.$ !== 'undefined' || typeof window.jQuery !== 'undefined') {
    // jQuery already present — do nothing
    return
  }

  // Minimal wrapper that implements a tiny subset of the jQuery API used
  // by many simple scripts: $(selector).each, .on, .click, and $(document).ready
  // This is NOT a full jQuery implementation. If the userscript expects
  // full jQuery, modify/disable that script or include the real jQuery.

  function $(selector) {
    // Support passing a function like $(fn) -> ready
    if (typeof selector === 'function') {
      return { ready: selector }
    }

    var els = []
    try {
      if (typeof selector === 'string') {
        els = Array.from(document.querySelectorAll(selector))
      } else if (selector instanceof Element || selector === window || selector === document) {
        els = [selector]
      } else if (selector && selector.length) {
        els = Array.from(selector)
      }
    } catch (e) {
      els = []
    }

    return {
      els: els,
      each: function (cb) {
        els.forEach(function (el, i) { cb.call(el, i, el) })
        return this
      },
      on: function (eventName, handler) {
        els.forEach(function (el) { el.addEventListener(eventName, handler) })
        return this
      },
      click: function (handler) {
        return this.on('click', handler)
      },
      html: function (val) {
        if (val === undefined) return els[0] && els[0].innerHTML
        els.forEach(function (el) { el.innerHTML = val })
        return this
      },
      text: function (val) {
        if (val === undefined) return els[0] && els[0].textContent
        els.forEach(function (el) { el.textContent = val })
        return this
      }
    }
  }

  // document ready helper
  $.ready = function (fn) {
    if (document.readyState !== 'loading') fn()
    else document.addEventListener('DOMContentLoaded', fn)
  }

  // Attach to window
  try {
    window.$ = window.jQuery = $
  } catch (e) {
    // ignore if cannot assign
  }
})
